/*
 * Copyright (C) 2013 47 Degrees, LLC
 *  http://47deg.com
 *  hello@47deg.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.pricy.me.adapters;
import java.io.IOException;
import java.net.UnknownHostException;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.atermenji.android.iconictextview.IconicFontDrawable;
import com.atermenji.android.iconictextview.icon.IconicIcon;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.pricy.me.MainActivity;
import com.pricy.me.R;
import com.pricy.me.StreamProductsActivity;
import com.pricy.me.UserProfileActivity;
import com.pricy.me.model.CategoryIcon;
import com.pricy.me.model.ProductAction;
import com.pricy.me.model.ProductExtended;
import com.pricy.me.model.User;
import com.pricy.me.utils.PrettyDate;



public class ProductAdapter extends BaseAdapter {

    private List<ProductExtended> data;
    private Context context;
	private Handler priceHandler;
	private ProgressDialog progressDialog;
	private ProductExtended product;

    public ProductAdapter(Context context, List<ProductExtended> data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public ProductExtended getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ProductExtended item = getItem(position);
        product = item;
        final ViewHolder holder;
        if (convertView == null) {
            LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = li.inflate(R.layout.product_row, parent, false);
            holder = new ViewHolder();
            holder.ivImage = (ImageView) convertView.findViewById(R.id.example_row_iv_image);
            holder.ivUserImage = (ImageView) convertView.findViewById(R.id.row_user_image);
            holder.ivCategory = (ImageView) convertView.findViewById(R.id.example_row_category);
            holder.ivUserInfos = (LinearLayout) convertView.findViewById(R.id.row_user_infos);
            holder.tvTitle = (TextView) convertView.findViewById(R.id.example_row_tv_title);
            holder.tvPrice = (TextView) convertView.findViewById(R.id.row_tv_price);
            holder.tvDate = (TextView) convertView.findViewById(R.id.row_date);
            holder.tvUsername = (TextView) convertView.findViewById(R.id.row_user_name);
            holder.ivBaIcon = (ImageView) convertView.findViewById(R.id.row_iv_baIcon);
            holder.btnBa = (LinearLayout) convertView.findViewById(R.id.idBonneaffaire);
            holder.nbrBonneaffaire = (TextView) convertView.findViewById(R.id.row_nbrbonneaffaire);
            holder.btnJl = (LinearLayout) convertView.findViewById(R.id.idJelai);
            holder.ivJlIcon = (ImageView) convertView.findViewById(R.id.row_iv_jlIcon);
            holder.nbrJelai = (TextView) convertView.findViewById(R.id.row_nbrjelai);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final String uploadProduct= context.getResources().getString(R.string.lienWebUpload) + "/product-";
        ImageLoader.getInstance().displayImage(uploadProduct+item.getId()+".jpg", holder.ivImage);
        ImageLoader.getInstance().displayImage(item.getUser().getPicture(), holder.ivUserImage);
        final IconicFontDrawable iconicFontDrawable = new IconicFontDrawable(context);
        iconicFontDrawable.setIcon(IconicIcon.HEART);
        if(item.isBonneAffaire()) iconicFontDrawable.setIconColor(Color.parseColor("#E74C3C"));
        else iconicFontDrawable.setIconColor(Color.parseColor("#929292"));
        holder.ivBaIcon.setBackgroundDrawable(iconicFontDrawable);
        
        final IconicFontDrawable iconicFontDrawable2 = new IconicFontDrawable(context);
        iconicFontDrawable2.setIcon(IconicIcon.OK_CIRCLE);
        if(item.isJelai()) iconicFontDrawable2.setIconColor(Color.parseColor("#E74C3C"));
        else iconicFontDrawable2.setIconColor(Color.parseColor("#929292"));
        holder.ivJlIcon.setBackgroundDrawable(iconicFontDrawable2);
        
        // Category
        final IconicFontDrawable iconicFontCat = new IconicFontDrawable(context);
        iconicFontCat.setIcon(item.getCategory().getIcon());
        iconicFontCat.setIconColor(Color.parseColor("#929292"));
        holder.ivCategory.setBackgroundDrawable(iconicFontCat);
        
        //holder.ivImage.setImageDrawable(item.getIcon());
        holder.tvTitle.setText(item.getTitle());
        PrettyDate pdate = new PrettyDate(item.getDate());
        holder.tvDate.setText(pdate.toString());
        holder.tvUsername.setText(item.getUser().getFirst_name()+" "+item.getUser().getLast_name());
        // Format currency
        NumberFormat currencyFormatter = NumberFormat.getNumberInstance();
        holder.tvPrice.setText(""+currencyFormatter.format(item.getPrice())+" "+item.getCurrency());
        holder.nbrBonneaffaire.setText(""+item.getNbrbonneaffaire());
        holder.nbrJelai.setText(""+item.getNbrjelai());
        
		holder.ivUserImage.setOnClickListener(userClicked);
		holder.ivUserInfos.setOnClickListener(userClicked);
        
        holder.tvPrice.setOnClickListener(new OnClickListener() {
			

			@Override
			public void onClick(View v) {
				
				progressDialog = new ProgressDialog(context);
		        progressDialog.setMessage(context.getString(R.string.loadingPrice));
		        progressDialog.setCancelable(false);
		        progressDialog.show();
		        
				final Thread worker = new Thread() {
					
					@Override
					public void run() {
						List<ProductAction> mData = ProductAction.load(item.getId(), context);
						if(mData.size() >0){
							Message msg = new Message();
							msg.obj = mData;
							priceHandler.sendMessage(msg);
						}
						progressDialog.dismiss();
					}
				};
				worker.start();
			}
		});
        
        priceHandler = new Handler(){
        	@Override
        	public void handleMessage(Message msg) {
        		final Dialog dialog = new Dialog(context);
		        dialog.setContentView(R.layout.price_list_view);
		        ListView mListView = (ListView) dialog.findViewById(R.id.price_lv_list);
		        @SuppressWarnings("unchecked")
				PriceAdapter mAdapter = new PriceAdapter(context, (List<ProductAction>) msg.obj);
		        mListView.setAdapter(mAdapter);
		        dialog.setTitle("Prix");
		        dialog.show();
        	}
        };
        
        holder.btnBa.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!item.isBonneAffaire()){
					iconicFontDrawable.setIconColor(Color.parseColor("#E74C3C"));
					item.setBonneAffaire(true);
					item.incNbrbonneaffaire();
					saveAction(item.getId(), 0, "true", null);
				}
				else{
					iconicFontDrawable.setIconColor(Color.parseColor("#929292"));
					item.setBonneAffaire(false);
					item.decNbrbonneaffaire();
					saveAction(item.getId(), 0, "false", null);
				}
				holder.nbrBonneaffaire.setText(""+item.getNbrbonneaffaire());
			}
		});
        
        holder.btnJl.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!item.isJelai()){
					// get prompts.xml view
					LayoutInflater li = LayoutInflater.from(context);
					View promptsView = li.inflate(R.layout.add_price, null);
	 
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							context);
	 
					// set prompts.xml to alertdialog builder
					alertDialogBuilder.setView(promptsView);
	 
					final EditText priceInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
					// final Button btnCurrency = (Button) promptsView.findViewById(R.id.btncurrency);
					
					final User user = new User();
					user.loadData(context);
	 
					// set dialog message
					alertDialogBuilder
						.setCancelable(false)
						.setPositiveButton(context.getString(R.string.add),
						  new DialogInterface.OnClickListener() {
						    public void onClick(DialogInterface dialog,int id) {
						    	iconicFontDrawable2.setIconColor(Color.parseColor("#E74C3C"));
						    	item.setJelai(true);
						    	item.incJelai();
						    	saveAction(item.getId(), 1, "true", priceInput.getText().toString());
						    	holder.nbrJelai.setText(""+item.getNbrjelai());
						    }
						  })
						.setNegativeButton(context.getString(R.string.nothks),
						  new DialogInterface.OnClickListener() {
						    public void onClick(DialogInterface dialog,int id) {
						    	iconicFontDrawable2.setIconColor(Color.parseColor("#E74C3C"));
						    	item.setJelai(true);
						    	item.incJelai();
						    	saveAction(item.getId(), 1, "true", null);
						    	dialog.cancel();
						    	holder.nbrJelai.setText(""+item.getNbrjelai());
						    }
						  });
	 
					// create alert dialog
					AlertDialog alertDialog = alertDialogBuilder.create();
					// show it
					alertDialog.show();
					
				}
				else{
					iconicFontDrawable2.setIconColor(Color.parseColor("#929292"));
					item.setJelai(false);
					item.decJelai();
					saveAction(item.getId(), 1, "false", null);
				}
				holder.nbrJelai.setText(""+item.getNbrjelai());
			}
		});
        


        return convertView;
    }

    static class ViewHolder {
        ImageView ivImage;
        ImageView ivUserImage;
        ImageView ivCategory;
        LinearLayout ivUserInfos;
        ImageView ivBaIcon;
        LinearLayout btnBa;
        TextView nbrBonneaffaire;
        LinearLayout btnJl;
        ImageView ivJlIcon;
        TextView nbrJelai;
        TextView tvTitle;
        TextView tvPrice;
        TextView tvDate;
        TextView tvUsername;
        Button bAction1;
        Button bAction2;
        Button bAction3;
    }

private void saveAction(final int productId, final int action, final String flag, final String price){
    	final Thread worker = new Thread() {
			
			@Override
			public void run() {
			User user = new User();
			user.loadData(context);
        	// Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            String priceText = "";
            if(price != null) priceText = "&price="+price;
            final String userProduct= context.getResources().getString(R.string.lien) + "api/product/action?user=";
            Log.e("PRICE",userProduct+user.getId()+"&product="+productId+"&action="+action+"&flag="+flag+priceText);
            HttpPost httppost = new HttpPost(userProduct+user.getId()+"&product="+productId+"&action="+action+"&flag="+flag+priceText);
            // Execute HTTP Post Request
			try {
				HttpResponse response = httpclient.execute(httppost);
				String reponse = EntityUtils.toString(response.getEntity());
				Log.e("REPONSE",reponse);
			} catch (UnknownHostException e) {
			} catch (HttpHostConnectException e) {
			} catch (ClientProtocolException e) {
			} catch (IOException e) {
			}
		}
	};
	worker.start();
}

OnClickListener userClicked = new OnClickListener() {
	
	@Override
	public void onClick(View v) {
		final Intent userProfile = new Intent(context, UserProfileActivity.class);
		Bundle bundle = new Bundle();
		bundle.putInt("id", product.getUser().getId());
		bundle.putString("username", product.getUser().getName());
		bundle.putString("picture", product.getUser().getPicture());
		bundle.putString("location", product.getUser().getAdress());
		userProfile.putExtra("infos", bundle);
    	context.startActivity(userProfile);
	}
};

}
